﻿using Furion;
using Furion.FriendlyException;
using Furion.RemoteRequest.Extensions;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace Mrhd.Core
{
    public class WeixinHelper
    {
        /// <summary>
        /// 用户登录解码api
        /// </summary>
        private static string LOGIN_URL;
        /// <summary>
        /// 获取访问令牌api
        /// </summary>
        private static string ACCESS_TOKEN;
        /// <summary>
        /// 创建小程序二维码api
        /// </summary>
        private static string CREATE_QRCODE;

        static WeixinHelper()
        {
            Weixin = new WeixinHelper();
            Weixin.AppId = App.Configuration["Wechat:AppId"];
            Weixin.Secret = App.Configuration["Wechat:AppSecret"];
            LOGIN_URL = App.Configuration["Wechat:LOGIN_URL"];
            ACCESS_TOKEN = App.Configuration["Wechat:ACCESS_TOKEN"];
            CREATE_QRCODE = App.Configuration["Wechat:CREATE_QRCODE"];
        }
        public string AppId { get; set; }
        public string Secret { get; set; }

        public static WeixinHelper Weixin { get; private set; }

        /// <summary>
        /// 获取用户登录信息（获取openid和会话密钥）
        /// </summary>
        /// <param name="code"></param>
        /// <param name="appId"></param>
        /// <param name="secret"></param>
        /// <returns></returns>
        public async Task<(string, string)> GetOpenIdAsync(string code, string appId = null, string secret = null)
        {
            var url = string.Format(LOGIN_URL, appId ?? AppId, secret ?? Secret, code);
            var msg = await url.GetAsStringAsync();
            var json = JObject.Parse(msg);
            if (json.ContainsKey("errcode"))
            {
                throw Oops.Oh($"解析用户OpenId出错，错误码：{json["errcode"].Value<string>()}，原因：" + json["errmsg"].Value<string>());
            }
            return (json["openid"].Value<string>(), json["session_key"].Value<string>());
        }

        /// <summary>
        /// 获取微信访问令牌
        /// </summary>
        /// <param name="appId"></param>
        /// <param name="secret"></param>
        /// <returns></returns>
        public async Task<string> GetAccessTokenAsync(string appId = null, string secret = null)
        {
            var url = string.Format(ACCESS_TOKEN, appId ?? AppId, secret ?? Secret);
            return await url.GetAsStringAsync();
        }

        /// <summary>
        /// 创建小程序二维码
        /// </summary>
        /// <param name="token">访问token</param>
        /// <param name="scene">场景</param>
        /// <param name="path">路径</param>
        /// <param name="width">宽度</param>
        /// <returns></returns>
        public async Task<byte[]> CreateQRCodeAsync(string token, string scene, string path, int width = 430)
        {
            var url = string.Format(CREATE_QRCODE, token);
            var data = await url.SetBody(new { path = path + scene, width }).PostAsync();
            var buffer = await data.Content.ReadAsByteArrayAsync();
            if (buffer != null)
            {
                return buffer;
            }
            var ret = await data.Content.ReadAsStringAsync();
            var json = JObject.Parse(ret);
            if (!json.ContainsKey("errcode")) return null;
            throw Oops.Oh($"创建小程序二维码出错，错误码：{json["errcode"].Value<string>()}，原因：" + json["errmsg"].Value<string>());
        }

    }


}
